<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <input type="text" id="txt">
    <button id="btn1">请求商品</button>
    <button id="btn2">请求品牌</button>
</body>
<script>
    // - 接口地址：http://icodeilife.club:3000/api/pro/search
    // - 请求方式：get
    // - 请求数据：sKey，要搜索的关键字
    // - 响应数据类型：json
    // - 响应数据内容：{"code": 200,"title": "请求成功","msg":[数据]}


    // - 接口地址：http://icodeilife.club:3000/api/pro/brand
    // - 请求方式：get
    // - 请求数据：kindKey，要请求的品牌的分类信息
    // - 响应数据类型：json
    // - 响应数据内容：{"code": 200,"title": "请求成功","msg":[数据]}


    const btn1 = document.getElementById("btn1");
    const btn2 = document.getElementById("btn2");
    const txt = document.getElementById("txt")

    btn1.onclick = function(){
        ajax({
            type:"get",
            url:"http://icodeilife.club:3000/api/pro/search",
            data:{
                sKey: txt.value
            },
            timeout: 40
        }).then(res=>{
            console.log(res)
        },err=>{
            console.log(err)
        })
    }

    function ajax(ops = {}){
        let {data={}, type="get", url, timeout=500} = ops;
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        if(type === "get"){
            url += "?" + str.slice(0, -1);
        }
        const xhr = new XMLHttpRequest();
        xhr.open(type, url);
        if(type === "post"){
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(str.slice(0,-1));
        }else{
            xhr.send();
        }
        return new Promise((resolve,reject)=>{
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && xhr.status === 200){
                    resolve(xhr.responseText);
                }else if(xhr.readyState === 4 && xhr.status !== 200){
                    reject(xhr.status)
                }
            }
            setTimeout(()=>{
                reject("timeout");
            }, timeout);
        })
    }




</script>
</html>